# app/device_cache.py
import redis
import json
import logging

from app.core.config import settings

logger = logging.getLogger(__name__)

class DeviceCache:
    def __init__(self):
        self.redis = None
        self.expire_time = settings.CACHE_EXPIRE_TIME  # 使用配置中的缓存过期时间

    async def init(self):
        """初始化Redis连接"""
        try:
            self.redis = redis.Redis(
                host="localhost",
                port=6379,
                db=0,
                decode_responses=True
            )
            if self.redis.ping():
                logger.info("Redis连接成功")
            else:
                raise ConnectionError("Redis ping失败")
        except Exception as e:
            logger.error(f"Redis连接失败: {e}")
            self.redis = None

    async def update_device(self, dev_id: str, update_data: dict):
        """更新设备缓存"""
        if not self.redis:
            return

        try:
            logger.debug(f"更新设备缓存: {dev_id}, {update_data}")
            # 获取当前设备数据
            current_data = await self.get_device(dev_id) or {}
            # 合并更新
            updated_data = {**current_data, **update_data}
            updated_data["dev_id"] = dev_id  # 确保包含dev_id

            device_json = json.dumps(update_data)
            # 使用管道提高效率
            with self.redis.pipeline() as pipe:
                pipe.hset("devices", dev_id, device_json)
                pipe.expire("devices", self.expire_time)
                pipe.execute()
        except Exception as e:
            logger.error(f"更新设备缓存失败: {e}")

    async def get_device(self, dev_id: str):
        """获取单个设备缓存"""
        if not self.redis:
            return None

        try:
            logger.debug(f"获取设备缓存: {dev_id}")
            device_json = self.redis.hget("devices", dev_id)
            return json.loads(device_json) if device_json else None
        except Exception as e:
            logger.error(f"获取设备缓存失败: {e}")
            return None

    async def get_all_devices(self):
        """获取所有设备缓存"""
        if not self.redis:
            return []

        try:
            devices = self.redis.hgetall("devices")
            return [json.loads(v) for v in devices.values()] if devices else []
        except Exception as e:
            logger.error(f"获取所有设备缓存失败: {e}")
            return []

    async def batch_update(self, devices: list):
        """批量更新设备缓存"""
        if not self.redis or not devices:
            return

        try:
            # 创建设备字典 {dev_id: device_json}
            device_dict = {}
            for device in devices:
                # 确保设备数据包含 'dev_id'
                if "dev_id" not in device:
                    logger.warning(f"设备数据缺少 'dev_id' 键: {device}")
                    continue
                device_json = json.dumps(device)
                device_dict[device["dev_id"]] = device_json

            # 批量更新
            if device_dict:
                # 使用管道批量操作
                with self.redis.pipeline() as pipe:
                    pipe.hmset("devices", device_dict)
                    pipe.expire("devices", self.expire_time)
                    pipe.execute()
        except Exception as e:
            logger.error(f"批量更新设备缓存失败: {e}")


    async def clear_cache(self):
        """清理缓存"""
        if not self.redis:
            return

        try:
            self.redis.delete("devices")
            logger.info("清理设备缓存成功")
        except Exception as e:
            logger.error(f"清理设备缓存失败: {e}")
# 全局设备缓存
device_cache = DeviceCache()